import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { getHomeDataApi } from '../api'

export const fetchHomeDataAction = createAsyncThunk(
  'homeDatas',
  async (_, { rejectWithValue }) => {
    try {
      const res = await getHomeDataApi()
      return res.data
    } catch (error) {
      return rejectWithValue(error)
    }
  }
)

export interface HomeState {
  hospitals: any[]
  nav2s: any[]
  navs: any[]
  slides: any[]
  loading: boolean
}
const initialState: HomeState = {
  hospitals: [],
  nav2s: [],
  navs: [],
  slides: [],
  loading: true
}
const homeSlice = createSlice({
  name: 'home',
  initialState: initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchHomeDataAction.pending, (state) => {
        state.loading = true
      })
      .addCase(fetchHomeDataAction.fulfilled, (state, action) => {
        const { slides, nav2s, hospitals } = action.payload
        state.slides = slides || []
        state.nav2s = nav2s || []
        state.hospitals = hospitals || []
        state.loading = false
      })
      .addCase(fetchHomeDataAction.rejected, (state) => {
        state.loading = false
      })
  }
})

export default homeSlice.reducer
